import axios from "axios";
import errorCode from "@/utils/errorCode";
import { axiosURL } from "./request-URI.js";
import { Spin } from "view-design";
import store from "@/store";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const service = axios.create({
    baseURL: axiosURL,
    timeout: 500000,
});
// request拦截器
service.interceptors.request.use(
    (config) => {
        // isSpin 是否启用加载效果
        if (typeof config.isSpin === "undefined" || config.isSpin === true) {
            // 加载中效果
            Spin.show({
                render: (h) => {
                    return h("div", [
                        h("Icon", {
                            class: "spin-icon-load",
                            style: "animation: ani-demo-spin 1s linear infinite;",
                            props: {
                                type: "ios-loading",
                                size: "30",
                            },
                        }),
                        h("div", "加载中"),
                    ]);
                },
            });
        }
        config.headers["Authorization"] = store.getters.token;
        config.headers["TENANTID"] = store.getters.tenantId;
        return config;
    },
    (error) => {
        Promise.reject(error);
    }
);
// 响应拦截器
service.interceptors.response.use(
    (res) => {
        // 取消加载中
        Spin.hide();
        // 未设置状态码则默认成功状态
        const code = res.data.code || 10000;
        const status = res.status || 200;
        // 获取错误信息
        const message = errorCode[code] || res.data.msg || errorCode.default;
        if (status !== 200) {
            return Promise.reject(message);
        } else {
            if (code !== 10000) {
                return Promise.reject(res.data);
            }
            if (
                res.config.url.includes("/export/export") ||
                res.config.url.includes("uploadFile/downloadFile") ||
                res.config.url.includes("hcaControlPlan/exportHcaControlPlan")
            ) {
                return res;
            } else {
                return res.data;
            }
        }
    },
    (error) => {
        Spin.hide();
        return Promise.reject(error);
    }
);

export default service;
